package com.dfdchem.imd.kaiwu.manager;

import android.content.Context;

import com.dfdchem.imd.kaiwu.R;
import com.dfdchem.imd.kaiwu.util.Log;
import com.dfdchem.imd.kaiwu.util.VersionUtil;

import org.jetbrains.annotations.NotNull;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 添加UA的拦截器
 * @author yqq
 */
public class UAInterceptor implements Interceptor {
    private Context context;

    public UAInterceptor(Context context) {
        this.context = context;
    }

    private static final String TAG = "UAInterceptor";
    private static final String UA = "User-Agent";

    @Override
    public Response intercept(@NotNull Chain chain) throws IOException {
        Request request = chain.request();

        String oldUA = request.header(UA);
        if (oldUA == null) {
            oldUA = "okhttp/4.7.2";
        }
        //UA 格式为 kaiwu/1.0.0
        String newUA = oldUA + " " + context.getResources().getString(R.string.app_host) + "/" + VersionUtil.getAppVersionName(context);

        Request newRequest = chain.request().newBuilder()
                .removeHeader(UA)
                .addHeader(UA, newUA)
                .build();
        return chain.proceed(newRequest);
    }
}
